
<?php
function __startsWith($haystack, $needle) {
    $length = strlen($needle);
    return (substr($haystack, 0, $length) === $needle);
}

function __endsWith($haystack, $needle) {
    $length = strlen($needle);
    $start = $length * -1; //negative
    return (substr($haystack, $start) === $needle);
}
error_reporting(1);
function getLatLong($address) {

   //$prepAddr = str_replace(' ','+',$address);
        $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.urlencode($prepAddr).'&sensor=false');
        $output= json_decode($geocode);
        $latitude = $output->results[0]->geometry->location->lat;
        $longitude = $output->results[0]->geometry->location->lng;
	 return $latitude . ',' . $longitude;
}
?>

<script type="text/javascript">
    var aho;
    var aho2;
    var TrainStations, BusStops,SubWays,NearbyPlaces;
    var glob;
    var output='';
    function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
        var R = 6371; // Radius of the earth in km
        var dLat = deg2rad(lat2-lat1);  // deg2rad below
        var dLon = deg2rad(lon2-lon1);
        var a =
            Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
            Math.sin(dLon/2) * Math.sin(dLon/2)
        ;
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c; // Distance in km
        return Math.round(d*100)/100;
    }

    function deg2rad(deg) {
        return deg * (Math.PI/180)
    }
    var nearby;
    var request;

    var counter=1;

    var result;
    var marker;
    var service;
    var map;
     var directionsService = new google.maps.DirectionsService();
               var directionsDisplay = new google.maps.DirectionsRenderer();
function GetDirections(){
    <? if (("LISTING_TYPE" == $data[0]) && (!empty($listing))) { ?>
      var latlng='<?=$listing["Listing"]["latlng"]?>';
      latlng=latlng.split(',');   
      <?}?>
                  var address=document.getElementById('address').value;
          var selectedMode = document.getElementById('mode').value;
     var request = {
                origin: address, 
                destination: new google.maps.LatLng(latlng[0],latlng[1]),
                travelMode: google.maps.TravelMode[selectedMode]
              };

              directionsService.route(request, function(response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                  directionsDisplay.setDirections(response);
                }
              });
}
    function initialize() {

        var mapOptions = {
            center: new google.maps.LatLng(51.4924186,-0.2609205),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);
// BEGIN DIRECTIONS
          

              directionsDisplay.setMap(map);
              directionsDisplay.setPanel(document.getElementById('panel'));

             
     // END DIRECTIONS

        var geocoder = new google.maps.Geocoder();

        var start ;
        map.setZoom(11);
        var infowin;
        
      <? if (("LISTING_TYPE" == $data[0]) && (!empty($listing))) { ?>
  var map2 = new google.maps.Map(
      document.getElementById('sv'), mapOptions);
      <? if (("LISTING_TYPE" == $data[0]) && (!empty($listing))) { ?>
      var latlng='<?=$listing["Listing"]["latlng"]?>';
      latlng=latlng.split(',');
      <?}?>
  var panoramaOptions = {
    position: new google.maps.LatLng(latlng[0],latlng[1]),
    pov: {
      heading: 34,
      pitch: 10
    }
  };
  var panorama = new  google.maps.StreetViewPanorama(document.getElementById('sv'),panoramaOptions);
  map2.setStreetView(panorama);
   <? } ?>

<?
if (("LISTING_TYPE" == $data[0]) && (!empty($listing))) {
    ?>
                start='<?= $listing['Listing']['address_1']; ?>';

                geocoder.geocode( { 'address': start}, function(results2, status) {
                    setTimeout('', 100);
                    if (status == google.maps.GeocoderStatus.OK) {
    <?php
    $out = '<div id="listing-rate" style="vertical-align: middle;padding-bottom: 2px;padding-top: 2px;width: 165px">';
    if ((($i_AVGRating * 2) % 2) == 0) {
        $i_MaxEn = $i_AVGRating;
        $i_MaxDis = 5 - $i_MaxEn;
        $b_Half = false;
    } else {
        $i_MaxEn = $i_AVGRating - 0.5;
        $i_MaxDis = 5 - ($i_MaxEn + 1);
        $b_Half = true;
    }
    for ($i = 0; $i < $i_MaxEn; $i++) :
        $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_enabled.png" width="15"/>';
    endfor;
    if ($b_Half):
        $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_half.png" width="15"/>';
    endif;
    for ($i = 0; $i < $i_MaxDis; $i++) :
        $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_disabled.png" width="15"/>';
    endfor;
    $out = $out . '<span style="float: right;">&nbsp;&nbsp;' . $i_TotalReview . ' мнения</span>';
    $out = $out . '<br/>' . $listing['Listing']['address_1'];
    $out = $out . '<div style="clear: both;"></div>';
    $out = $out . '</div>';

    $out = str_replace('"', "'", $out);

    $link = '<a href="' . SITE_WEBROOT . $listing["Listing"]["url_title"] . '-l' . $listing["Listing"]["id"] . '.html">' . htmlspecialchars($listing["Listing"]["title"]) . '</a>';
    $link = str_replace('"', "'", $link);
    ?>

                        infowin = new google.maps.InfoWindow({
                            content:"<div class='wam-googft-info-window'><?= $link ?><br><?= $out ?></div>"
                        });
                        marker = new google.maps.Marker({ map: map});
                        marker.setVisible(false);
                        /*google.maps.event.addListener(marker, 'click', function() {
                                            infowin.open(map,marker);
                                        });*/
                        map.setCenter(results2[0].geometry.location);
                        marker.setPosition(results2[0].geometry.location);
                        marker.setVisible(true);
                       } else {
                        // alert("Geocode was not successful for the following reason: " + status);
                    }
                });
                // setTimeout('', 100);


                //                var marker;
    <?
}
$number = 1;
foreach ($listings as $listing) {
    $link = $number.'&nbsp;<a href="' . SITE_WEBROOT . $listing["Listing"]["url_title"] . '-l' . $listing["Listing"]["id"] . '.html">' . htmlspecialchars($listing["Listing"]["title"]) . '</a>';
    $link = str_replace('"', "'", $link);
    $out = '<div id="listing-rate" style="vertical-align: middle;padding-bottom: 2px;padding-top: 2px;width: 165px">';
    if ((($i_AVGRating * 2) % 2) == 0) {
        $i_MaxEn = $i_AVGRating;
        $i_MaxDis = 5 - $i_MaxEn;
        $b_Half = false;
    } else {
        $i_MaxEn = $i_AVGRating - 0.5;
        $i_MaxDis = 5 - ($i_MaxEn + 1);
        $b_Half = true;
    }
    for ($i = 0; $i < $i_MaxEn; $i++) :
        $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_enabled.png" width="15"/>';
    endfor;
    if ($b_Half):
        $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_half.png" width="15"/>';
    endif;
    for ($i = 0; $i < $i_MaxDis; $i++) :
        $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_disabled.png" width="15"/>';
    endfor;
    $out = $out . '<span style="float: right;">&nbsp;&nbsp;' . $i_TotalReview . ' мнения</span>';
    $out = $out . '<br/>' . $listing['Listing']['address_1'];
    $out = $out . '<div style="clear: both;"></div>';
    $out = $out . '</div>';

    $out = str_replace('"', "'", $out);
    ?>


                start='<?= $listing['Listing']['address_1']; ?>';
                var latlng='<?=$listing["Listing"]["latlng"]?>';
                     latlng=latlng.split(',');   
            //    geocoder.geocode( { 'address': start}, function(results2, status) {
            //        setTimeout('', 100);
               //     if (status == google.maps.GeocoderStatus.OK) {
                        var number = <?php echo $number; $number++; ?>;
                        marker = new google.maps.Marker({ 
                            map: map,
                            icon:'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='+ number +'|FF776B|000000',
                            //position:results2[0].geometry.location
                            position:new google.maps.LatLng(latlng[0],latlng[1])
                        });
                        var contentstr="<div class='wam-googft-info-window'><?= $link ?><br><?= $out ?></div>";
                        marker.content=contentstr;
                        marker.setVisible(false);
                        var veh_infowindow = new google.maps.InfoWindow({
                            content:contentstr
                        });

                        google.maps.event.addListener(marker, 'click', function() {
                            veh_infowindow.setContent(this.content);
                            veh_infowindow.open(map,this);
                        });
                        //map.setCenter(results2[0].geometry.location);
                        map.setCenter(new google.maps.LatLng(latlng[0],latlng[1]));
                        // marker.setPosition(results2[0].geometry.location);
                        marker.setVisible(true);


          //          }
           //     });
<? } ?>
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style type="text/css">
    #map-canvas { height: 200px; }
</style>

<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
 <script>
$(function() {
$( "#accordion" ).accordion({collapsible: true,active: false});
$( "#accordion2" ).accordion({collapsible: true,active: false});
});
</script>
<script>
        function getCheckedBoxes(chkboxName) {
  var checkboxes = document.getElementsByName(chkboxName);
  var checkboxesChecked = [];
  // loop over them all
  for (var i=0; i<checkboxes.length; i++) {
     // And stick the checked ones onto an array...
     if (checkboxes[i].checked) {
        checkboxesChecked.push(checkboxes[i]);
     }
  }
  // Return the array if it is non-empty, or null
  return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}

// Call as

function filter_locations ()
  {
   var checkedBoxes = getCheckedBoxes("Location[]");
   var str='';
   for (i=0;i<checkedBoxes.length;i++){
       str=str+checkedBoxes[i].value.replace(' ','-')+'+';
    }
    str=str.substr(0,str.length-1);
  window.location.assign(location.href+'/'+str);
  }
  function filter_categories ()
  {
   var checkedBoxes = getCheckedBoxes("Category[]");
   var str='';
   for (i=0;i<checkedBoxes.length;i++){
       
       str=str+checkedBoxes[i].value.replace(' & ','-').replace(' ','-')+'+';
    }
     str=str.substr(0,str.length-1);
  window.location.assign(location.href+'/'+str);
  }
</script>


  <!-- tuannguyen2042: filter -->
  <script type="text/javascript">
    function loadChildCats(catId, locId){
      jQuery(".progress-indicator").fadeIn();
      
      jQuery.ajax({
        type: "GET",
        dataType: "html",
        evalScripts: true,
        url: "<?php echo Router::url(array('controller' => 'inits', 'action' => 'ajaxGetChildCats')) ?>/" + catId + "/" + locId,
        success: function(data, textStatus){
          jQuery(".progress-indicator").fadeOut();
          
          if (data.length > 5)            
            $("#childcats"+catId).html(data).show();
                      
        }
      });
    }
    
    function filterListings(page, ind){
      page = typeof page !== 'undefined' ? page : 1;
      ind = typeof ind !== 'undefined' ? ind : "";
      
      jQuery(".progress-indicator").fadeIn();
      
      jQuery.ajax({
        type: "POST",
        dataType: "html",
        evalScripts: true,
        url: "<?php echo Router::url(array('controller' => 'inits', 'action' => 'ajaxFilterListings')) ?>/" + page + "/" + ind,
        data: jQuery("#filterform").serialize(),
        success: function(data, textStatus){
          jQuery(".progress-indicator").fadeOut();
          jQuery("#listings").html(data);
        }        
      });
    }
  </script>
  <!-- end -->     

<?php
/*
echo $form->create('Listings',array('action' => 'search'));
echo $form->input('Listings.search',array('label'=>'Search For'));
echo $form->input('Listings.nearby',array('label'=>'Near'));
echo $form->end('Search');*/
?>

<?php if (in_array($data[0], array('LOCATION_TYPE', 'LOCATIONS_TYPE', 'CATEGORYLOCATION_TYPE', 'CATEGORY_TYPE'))) { ?>
  <div class="listings index">
    <h1>
    <?php
      if ($data[0] == "LOCATION_TYPE") {
        echo htmlspecialchars($data[1]["Location"]["name"]);
      } 
      elseif ($data[0] == "CATEGORYLOCATION_TYPE") {
        echo htmlspecialchars($data[1]["Category"]["name"] . ' в ' . $data[2]["Location"]["name"]);
      }
      elseif ($data[0] == "CATEGORY_TYPE") {
        echo htmlspecialchars($data[1]["Category"]["name"]);
      }
    ?>
    </h1>
          
    
    <!-- tuannguyen2042: filter -->
    <?php if (count($listings) > 0 || count($allCategories) > 0): ?>
        
    <?php 
    //var_dump($data);
    //var_dump($locations); 
    ?>   
    
    <div id="filter" class="box">
      <div class="box-caption-fixed">Filter</div>
      <div class="box-content-fixed ">
        <form method="POST" action="" id="filterform">
          <input type="hidden" name="filterType" value="<?php echo $data[0]; ?>" />
        
          <?php if (in_array($data[0], array('LOCATION_TYPE', 'LOCATIONS_TYPE'))): ?>
          <input type="hidden" name="currentLoc" value="<?php echo $data[1]['Location']['id']; ?>" />
          <?php endif; ?>
          
          <?php if (in_array($data[0], array('CATEGORYLOCATION_TYPE'))): ?>
          <input type="hidden" name="currentCat" value="<?php echo $data[1]['Category']['id']; ?>" />
          <input type="hidden" name="currentLoc" value="<?php echo $data[2]['Location']['id']; ?>" />
          <?php endif; ?>
          
          <?php if (in_array($data[0], array('CATEGORY_TYPE'))): ?>
          <input type="hidden" name="currentCat" value="<?php echo $data[1]['Category']['id']; ?>" />
          <?php endif; ?>
          
          <table border="0" cellpadding="5">
            <?php if (count($locations) > 0): ?>
            <tr valign="top">
              <td>
                <p><strong>Locations</strong></p>
                <div>
                  <?php foreach($locations as $location): ?>
                  <ul class="filtercat">
                    <li>
                      <input type="checkbox" onclick="filterListings()" name="loc<?php echo $location['Location']['id']; ?>" value="<?php echo $location['Location']['id']; ?>" style="margin-top:3px;" />                      
                      <?php if ($data[0] == 'CATEGORYLOCATION_TYPE'): ?>
                      <a href="<?php echo SITE_WEBROOT . $data[2]['Location']['url_title'] . '/' .$data[1]['Category']['url_title'].'/'. $location['Location']['url_title']; ?>"><?php echo htmlspecialchars($location['Location']['name']); ?></a>
                      <?php else: ?>
                      <a href="<?php echo SITE_WEBROOT . $data[1]['Location']['url_title'] . '/' . $location['Location']['url_title']; ?>"><?php echo htmlspecialchars($location['Location']['name']); ?></a>
                      <?php endif; ?>                                                                                        
                    </li>
                  </ul>                  
                  <?php endforeach; ?>
                </div>
              </td>
            </tr>
              <?php endif; ?>
              <?php if (count($allCategories) > 0): ?>
              <tr valign="top">
              <td>
                <p><strong>Categories</strong></p>
                <div>                  
                  <?php 
                    foreach($allCategories as $category): 
                      $category_name = trim($category['Category']['name']);                                            
                  ?>
                  <ul class="filtercat">
                    <li>
                      <input type="checkbox" onclick="filterListings()" name="cat<?php echo $category['Category']['id']; ?>" value="<?php echo $category['Category']['id']; ?>" style="margin-top:3px;" />
                      
                      <?php if (in_array($data[0], array('LOCATION_TYPE', 'LOCATIONS_TYPE', 'CATEGORYLOCATION_TYPE'))): ?>
                      <a href="<?php echo SITE_WEBROOT . $locationPath . $category['Category']['url_title']; ?>"><?php echo $category_name; ?></a>
                      <?php elseif (in_array($data[0], array('CATEGORY_TYPE'))): 
                        $allCategoriesPrefixURL = SITE_WEBROOT . $data[1]['CATEGORY_PATH_URL'][(count($data[1]['CATEGORY_PATH_URL']) - 1)];
                      ?>                                            
                      <a href="<?php echo SITE_WEBROOT . $allCategoriesPrefixURL . '/' . $category['Category']['url_title']; ?>"><?php echo $category_name; ?></a>
                      <?php endif; ?>
                      <!--
                      <a href="javascript:void(0)" onclick="loadChildCats(<?php echo $category['Category']['id'].','.$data[1]['Location']['id']; ?>)"><?php echo $category_name; ?></a>                    
                      <ul class="childCat" id="childcats<?php echo $category['Category']['id']; ?>" style="display:none;"></ul>
                      -->
                    </li>
                  </ul>
                  
                  <?php endforeach; ?>
                </div>
              </td>
            </tr>
            <?php endif; ?>
          </table>
        </form>
      </div>
    </div>
    <?php endif; ?>
    <!-- end filter -->
    
    

    <?php if (!empty($locations) && !isset($this->params['named']['ind']) && empty($this->params['named']['ind'])): ?>
    <div class="box" id="accordion">
        <div class="box-caption-fixed">City in <?php echo $data[1]['Location']['name']; ?>
		</div>
        <div class="box-content-fixed ">
                <form action="#" method="POST" name="frm1"> 
                    <table border="0" class="categories">
						<?php
						if (!empty($locations)) {
							$i = 1;
							foreach ($locations as $location) {
								if ($i == 1)
									echo '<tr>';

								echo '<td style="vertical-align:top; width:49%">';
								//echo '<img src="' . SITE_WEBROOT . 'img/default.gif" alt="' . htmlspecialchars($location['Location']['name']) . '" width="20" height="20" />';
								echo '<input type="checkbox" value="'.htmlspecialchars($location['Location']['name']).'" name="Location[]"/>';
								if($data[0]=='CATEGORYLOCATION_TYPE'){
									echo '<a href="' . SITE_WEBROOT . $data[2]['Location']['url_title'] . '/' .$data[1]['Category']['url_title'].'/'. $location['Location']['url_title'] . '" class="countable categories">' . htmlspecialchars($location['Location']['name']) . '</a>';
							}else{
								echo '<a href="' . SITE_WEBROOT . $data[1]['Location']['url_title'] . '/' . $location['Location']['url_title'] . '" class="countable categories">' . htmlspecialchars($location['Location']['name']) . '</a>';
							}
								echo '</td>';

								if ($i % 2 == 0)
									echo '</tr>';
								$i++;
							}
						}
						?>
                        <tr><td><input type="button" style="width:100px;"value="Filter" onclick="filter_locations()"/></td></tr>
                    </table>
                </form>
            </div>
    </div>
    <?php endif; ?>


    <?php
		if (!empty($allCategories) && !isset($this->params['named']['ind']) && empty($this->params['named']['ind']) ) {
        if ($data[0] == "LOCATION_TYPE" || $data[0] == "LOCATIONS_TYPE" ) {
            ?>

                <div class="box" id="accordion2" >
                    <div class="box-caption-fixed">Категории в <?php echo htmlspecialchars($data[1]["Location"]["name"]); ?>
					</div>
                    <div class="box-content-fixed " >
                        <table border="0" class="categories">
							<?php
							if (!empty($allCategories)) {
								$i = 1;
								foreach ($allCategories as $category) {
									if ($i == 1) {
										echo '<tr>';
									}
									echo '<td style="vertical-align: top; width: 49%;">';
									//echo '<img src="' . SITE_WEBROOT . 'img/default.gif" alt="' . htmlspecialchars($category["Category"]["name"]) . '" width="20" height="20" />';
									echo '<input type="checkbox" value="'.htmlspecialchars($category["Category"]["name"]).'" name="Category[]"/>';                            
									//echo '<a href="'.SITE_WEBROOT.$data[1]["Location"]["url_title"].'/'.$category["Category"]["url_title"].'" class="countable categories">'.htmlspecialchars($category["Category"]["name"].' в '.$data[1]["Location"]["name"]).'</a>';
									echo '<a href="' . SITE_WEBROOT . $locationPath . $category["Category"]["url_title"] . '" class="countable categories">' . htmlspecialchars($category["Category"]["name"]) . '</a>';
									echo '</td>';
									if ($i == 2) {
										echo '</tr>';
									}

									if ($i == 2) {
										$i = 1;
									} else {
										$i++;
									}
								}
								if ($i != 1) {
									echo '</tr>';
								}
							}
							?>
                             <tr><td><input type="button" style="width:100px;" value="Filter" onclick="filter_categories()"/></td></tr>
                        </table>
                    </div>
                    Каталог с фирми в град <?php echo $data[1]["Location"]["name"]; ?>.Бизнес контакти и адреси за населено място <?php echo $data[1]["Location"]["name"]; ?>.Онлайн справочник и фирмен регистър на <?php echo $data[1]["Location"]["name"]; ?> в който ще намерите безплатна полезна информация за фирмите в <?php echo $data[1]["Location"]["name"]; ?>.
                </div>

                <?php
            }
            else if ($data[0] == "CATEGORYLOCATION_TYPE") {
                ?>

                <div class="box" >
                    <div class="box-caption-fixed">Категории в <?php echo htmlspecialchars($data[1]["Category"]["name"]); ?></div>
                    <div class="box-content-fixed " >
                        <table border="0" class="categories">
            <?php
            if (!empty($allCategories)) {
                //$allCategoriesPrefixURL = SITE_WEBROOT.$data[2]["Location"]["url_title"].'/'.$data[1]["CATEGORY_PATH_URL"][(count($data[1]["CATEGORY_PATH_URL"]) - 1)];
                $i = 1;
                foreach ($allCategories as $category) {
                    if ($i == 1) {
                        echo '<tr>';
                    }
                    echo '<td style="vertical-align: top; width: 49%;">';
                    echo '<img src="' . SITE_WEBROOT . 'img/default.gif" alt="' . htmlspecialchars($category["Category"]["name"]) . '" width="20" height="20" />';
                    echo '<a href="/' . $locationPath . $category["Category"]["url_title"] . '" class="countable categories">' . htmlspecialchars($category["Category"]["name"]) . '</a>';
                    echo '</td>';
                    if ($i == 2) {
                        echo '</tr>';
                    }

                    if ($i == 2) {
                        $i = 1;
                    } else {
                        $i++;
                    }
                }
                if ($i != 1) {
                    echo '</tr>';
                }
            }
            ?>
                        </table>
                    </div>
                </div>

            <?php
        }
        else if ($data[0] == "CATEGORY_TYPE") {
            ?>
                <div class="box" >
                    <div class="box-caption-fixed">Категории в <?php echo htmlspecialchars($data[1]["Category"]["name"]); ?></div>
                    <div class="box-content-fixed " >
                        <table border="0" class="categories">
            <?php
            if (!empty($allCategories)) {
                $allCategoriesPrefixURL = SITE_WEBROOT . $data[1]["CATEGORY_PATH_URL"][(count($data[1]["CATEGORY_PATH_URL"]) - 1)];

                $i = 1;
                foreach ($allCategories as $category) {
                    if ($i == 1) {
                        echo '<tr>';
                    }
                    echo '<td style="vertical-align: top; width: 49%;">';
                    echo '<img src="' . SITE_WEBROOT . 'img/default.gif" alt="' . htmlspecialchars($category["Category"]["name"]) . '" width="20" height="20" />';
                    echo '<a href="' . $allCategoriesPrefixURL . '/' . $category["Category"]["url_title"] . '" class="countable categories">' . htmlspecialchars($category["Category"]["name"]) . '</a>';
                    echo '</td>';
                    if ($i == 2) {
                        echo '</tr>';
                    }

                    if ($i == 2) {
                        $i = 1;
                    } else {
                        $i++;
                    }
                }
                if ($i != 1) {
                    echo '</tr>';
                }
            }
            ?>
                        </table>
                    </div>
                </div>
            <?php
        }
    }
    ?>

        <?php
        if (!empty($data[1]["Location"]["body"])) {
            echo '<br />';
            echo $data[1]["Location"]["body"];
            echo '<br />';
        } else if (!empty($data[1]["Category"]["body"])) {
            echo '<br />';
            echo $data[1]["Category"]["body"];
            echo '<br />';
        }

        echo "<br/>";
        echo '<div id="listings">';
        
        if(!isset($this->params['named']['ind']) && empty($this->params['named']['ind']))   {
        ?>
        
        <div class="listings">
            <table cellspacing="0" cellpadding="0" width="100%">
                    <?php
                    $i = 0;
                    $pagenum = $this->Paginator->params();
                    $pagenum = $pagenum['page'];
                    $pagenum = $pagenum - 1;
                    $iiii = 0;
                    foreach ($listings as $listing) {
                        $kk = ($pagenum * 10) + ($iiii + 1);
                        $iiii = $iiii+1;
                        $class = null;
                        if ($i++ % 2 == 0) {
                            $class = ' class="altrow"';
                        }
                        ?>
                    <tr <?php echo $class; ?>>
                        <td valign="top" style="padding-right: 5px; width: 125px;">
                            <div class="preview" style="margin-bottom: 10px;">
                                <img src="http://open.thumbshots.org/image.pxf?url=<?php echo urlencode($listing["Listing"]["url"]); ?>" alt="<?php echo htmlspecialchars($listing["Listing"]["url"]); ?>" />
                            </div>
                        </td>
                        <td valign="top" style="padding-right: 5px;">
                            <div class="title">
                        <?php echo $kk.'.&nbsp;&nbsp;<a href="' . SITE_WEBROOT . $listing["Listing"]["url_title"] . '-l' . $listing["Listing"]["id"] . '.html">' . htmlspecialchars($listing["Listing"]["title"]) . '</a>'; ?>


<br/>
<?php 

$last_but_one = count($listing["Listing"]["all_urls"]);
$last_but_one = $last_but_one -2;

$category_last = end(explode('/',$listing["Listing"]["all_urls"][$last_but_one]['url']));
$india_url = $listing["Listing"]["all_urls"][0]['url'];
$nagpur = $india_url.$category_last;
?>
Categories:  <?php echo $listing["Listing"]["all_urls"][$last_but_one]['name'];  ?> in 
<a href="<?php echo SITE_WEBROOT .$nagpur ; ?>" ><?php echo htmlspecialchars($listing["Listing"]["all_urls"][0]['name']); ?></a>&nbsp;/&nbsp;
<a href="<?php echo SITE_WEBROOT . $listing["Listing"]["all_urls"][$last_but_one]['url']; ?>" ><?php echo htmlspecialchars($listing["Listing"]["all_urls"][1]['name']); ?></a><br/>
<?php
echo "Telephone: ".$listing["Listing"]["landline"]."<br/>";
echo "Address : ";
if( trim($listing['Listing']['address_1']) != ""){
      echo $listing['Listing']['address_1'];
}
if( trim($listing['Listing']['address_2']) != ""){
      echo $listing['Listing']['address_2'];
}
$rr = $listing['Listing']['review_rate'];
$upperL = ceil($rr);
$lowerL = floor($rr);
$half = false;
if( $upperL != $lowerL){
    $half = true;
}

echo "<br/>";
echo "Total Review: ";
for ($i = 0; $i < 5; $i++) {
       if( $i< $lowerL ) {
        echo '<img src="' . SITE_WEBROOT . 'img/stars_enabled.png" width="15"/>';
       } else if ( $half ){
            echo '<img src="' . SITE_WEBROOT . 'img/stars_half.png" width="15"/>';
       } else {
            echo '<img src="' . SITE_WEBROOT . 'img/stars_disabled.png" width="15"/>';
       }
}
echo "&nbsp;&nbsp;".$listing['Listing']['review_c'];


 ?>

                            </div>
                            <div class="url"><?php echo htmlspecialchars($listing["Listing"]["url"]); ?></div>
                            <p><?php
                echo $htmlToText->html2text($listing["Listing"]["description"], 160, true);
                echo '</p>';
                  $ts=explode('<br/>',$listing['Listing']['train_stations']);
            $bs=explode('<br/>',$listing['Listing']['bus_stations']);
            $ss=explode('<br/>',$listing['Listing']['subway_stations']);
                        ?>
                                <?if (($ts[0]!=='')){?>
                            <strong>Train Station</strong>
                           <div><? echo $ts[0];}?></div>
                            <?if (($bs[0]!=='')){?>
                            <strong>Bus Station</strong>
                            <div><? echo $bs[0];}?></div>
                            <?if (($ss[0]!=='')){?>
                            <strong>Subway Station</strong>
                            <div><? echo $ss[0];}?></div>
            <?

               // }
            ?>
                            <script></script>

                        </td>
                    </tr>
                <?php } ?>
            </table>
			
        </div>
        <p>
			<?php
			} else { ?>
			<div class="listings">
				<table cellspacing="0" cellpadding="0" width="100%">
						<?php
						$i = 0;
						$pagenum = $this->Paginator->params();
						$pagenum = $pagenum['page'];
						$pagenum = $pagenum - 1;

						foreach ($listings as $listing) {
							$kk = ($pagenum * 10) + ($i + 1);
							$class = null;
							if ($i++ % 2 == 0) {
								$class = ' class="altrow"';
							}
							?>
						<tr <?php echo $class; ?>>
							<td valign="top" style="padding-right: 5px; width: 0px;">
							   <!--   <div class="preview" style="margin-bottom: 10px;">
									<img src="http://open.thumbshots.org/image.pxf?url=<?php echo urlencode($listing["Listing"]["url"]); ?>" alt="<?php echo htmlspecialchars($listing["Listing"]["url"]); ?>" />
								</div> -->
							</td>
							<td valign="top" style="padding-right: 5px;">
								<div class="title">
							<?php echo $kk.'.&nbsp;&nbsp;<a href="' . SITE_WEBROOT . $listing["Listing"]["url_title"] . '-l' . $listing["Listing"]["id"] . '.html">' . htmlspecialchars($listing["Listing"]["title"]) . '</a>'; ?>
								</div>
								<div class="url"><?php echo htmlspecialchars($listing["Listing"]["url"]); ?></div>
				   <?php //  Removed from line nunmber 415-436 ?>
							</td>
						</tr>
					<?php } ?>
				</table>
			</div>
			<?php }
                echo $this->Paginator->counter(array(
                    'format' => __('Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%', true)
                ));
                ?>	</p>
				
<!-- NGuyen ANh -->
				
        <div class="paging">
    <?php

$pageOptions = $this->Paginator->params();
if( isset($this->params['named']['ind']) && !empty ($this->params['named']['ind']) ) {
    $ind = "/ind:".$this->params['named']['ind'];
} else {
    $ind = "";
}

$tttoo = $pageOptions['page'] / 4;
$start_pp = 1;
if($tttoo > 1 ){
    $start_pp = $pageOptions['page'] - 4;

}
$prev = $pageOptions['page'] - 1;
if($prev < 1) {
	$prev = '';
}


$next_pages = $pageOptions['pageCount'];
$end_pp = $pageOptions['page'] + 4;

if( $end_pp > $next_pages ){
	$end_pp = $pageOptions['pageCount'];
} 
$next_pa = $end_pp + 1;
if( $next_pa > $pageOptions['pageCount'] ) {
    $next_pa = '';	
}

//var_dump($data);
//var_dump($this->params);

if( isset($prev) && !empty($prev) ) {
   echo "<a href='http://".$_SERVER['SERVER_NAME'].Router::url('/').$data[1]['Location']['name'].$ind."/page:".$prev."' ><< Previous</a>";
} else {
 echo "<< Previous";
}
if ($data[0] == "LOCATIONS_TYPE") {
   $locationname = $this->params['pass'][0].'/'.str_replace(" ","+",$this->params['pass'][1]);
}
//tuannguyen2042 added 02/11/2014
elseif (in_array($data[0], array('CATEGORYLOCATION_TYPE', 'CATEGORY_TYPE', 'LOCATION_TYPE'))){   
  $locationname = implode('/', $this->params['pass']);
}
//end
else{
    $locationname=$data[1]['Location']['name'];
}

for( $i = 1; $i <= $pageOptions['pageCount'] ; $i++ ){
if( $i >= $start_pp && $i <= $end_pp ) {
		if( $i == $pageOptions['page']) {
		    echo $i." | ";
		} else {
		        echo "<a href='http://".$_SERVER['SERVER_NAME'].Router::url('/').$locationname.$ind."/page:".$i."' >".$i." | </a>";
		}
}
}

if( isset($next_pa) && !empty($next_pa) ) {
   echo "<a href='http://".$_SERVER['SERVER_NAME'].Router::url('/').$locationname.$ind."/page:".$next_pa."' >Next >></a>";
} else {
 echo " Next >>";
}


//tuannguyen2042 added 02/11/2014
if (in_array($data[0], array('CATEGORYLOCATION_TYPE', 'LOCATION_TYPE'))){
  echo "<br/>";
  $a = range("A", "Z");
  foreach($a as $char) {
    if(in_array($char, $links_p)) {
 	    echo "<a href='http://".$_SERVER['SERVER_NAME'].Router::url('/').$this->params['pass'][0]."/ind:".$char."/sort:title/direction:asc' >".$char."&nbsp;</a>";
    } 
    else {
    	echo $char;
    }
  }
}
//end

?>
        </div>
			</div>

                            <?php
                            // static
                            if (($data[0] == "CATEGORYLOCATION_TYPE") || ($data[0] == "CATEGORY_TYPE")) {
                                /* echo '<br />';
                               

                                  for($i = 0, $staticLocationsSize = count($staticLocations); $i < $staticLocationsSize; $i++) {
                                  echo '<a href="'.SITE_WEBROOT.$staticLocations[$i][1].'/'.$data[1]["Category"]["url_title"].'/">'.htmlspecialchars($data[1]["Category"]["name"].' в '.$staticLocations[$i][0]).'</a>';
                                  echo ' | ';
                                  }
                                  echo '<a href="'.SITE_WEBROOT.$data[1]["Category"]["url_title"].'/">'.htmlspecialchars('List of '.$data[1]["Category"]["name"]).' в UK</a>';
                                  echo ' | ';
                                  echo '<a href="'.SITE_WEBROOT.'">Moving Directory</a>'; */
                            }
                            ?>

    </div>
        <?php
    } 
    
    elseif (("LISTING_TYPE" == $data[0]) && (!empty($listing))) { ?>
	<div class="center-menu">					
								<div class="center-left-one">
									<ul>
										<li><a href="javascript:void(0);">YouTuBe</a></li>
										<li><a href="javascript:void(0);">Content</a></li>
										<li><a href="javascript:void(0);">Address</a></li>
										<li><a href="javascript:void(0);">Comment</a></li>
										<div class="clear"></div>
									</ul>
								</div>
	</div>								
<div class="listings view">
	<div class="list-youtube">
        <h1><?php echo htmlspecialchars($listing['Listing']['title']); ?></h1>
     	<b><?php

     	//echo $listing['Listing']['added_by_user_group'];exit;
		if( $listing['Listing']['added_by_user_group'] != 2 ||  $listing['Listing']['added_by_user_group'] == 1 ||  $listing['Listing']['added_by_user_group'] == 0) {
		if($this->Session->check('Auth.User')){
			$permissions = $listing['Listing']['edit_permission'];
			if(trim($permissions) != ""){
				$permssions = explode(',',$permissions);
				foreach($permssions as $edit){
					if($edit == $this->Session->read('Auth.User.id')){
						$permissions = true;
						break;
					} else {
						$permissions = false;
					}
				}
			} else {
				$permissions = false;
			}

			$claimed = $listing['Listing']['claim_by_users'];
			if(trim($claimed) != ""){
				$claimed= explode(',',$claimed);
				//print_r($claimed);exit;
				foreach($claimed as $edit){
					if($edit == $this->Session->read('Auth.User.id')){
						$claimed = true;
						break;
					} else {
						$claimed = false;
					}
				}
			} else {
				$claimed = false;
			}
			if( $permissions ){
				echo $this->Html->link(__('Edit', true), array('admin'=>false, 'plugin'=>false, 'controller'=>'listings', 'action' => 'claim', $listing['Listing']['id']), array ('style' => 'float: right;margin-top: -25px;'));
			} else if( $claimed ){
				echo "<b style='float: right;margin-top: -25px;' >You have claimed.</b>";
			} else {
				echo $this->Html->link(__('Claim Listing', true), array('admin'=>false, 'plugin'=>false, 'controller'=>'listings', 'action' =>'claim', $listing['Listing']['id'], 'claim'), array ('style' => 'float: right;margin-top: -25px;'));
			}
		}  else {
			echo $this->Html->link(__('Claim Listing', true), array('admin'=>false, 'plugin'=>false, 'controller'=>'listings', 'action' =>'claim', $listing['Listing']['id'], 'claim'), array ('style' => 'float: right;margin-top: -25px;'));
		}
	}
	?></b>
        <div id="listing-rate" style="vertical-align: middle;padding-bottom: 2px;padding-top: 2px;width: 165px">
			<?php
			if ((($i_AVGRating * 2) % 2) == 0) {
				$i_MaxEn = $i_AVGRating;
				$i_MaxDis = 5 - $i_MaxEn;
				$b_Half = false;
			} else {
				$i_MaxEn = $i_AVGRating - 0.5;
				$i_MaxDis = 5 - ($i_MaxEn + 1);
				$b_Half = true;
			}
			?>
			<?php for ($i = 0; $i < $i_MaxEn; $i++) : ?>
					<img src="<?php echo SITE_WEBROOT; ?>img/stars_enabled.png" width="15"/>
			<?php endfor; ?>
			<?php if ($b_Half): ?>
					<img src="<?php echo SITE_WEBROOT; ?>img/stars_half.png" width="15"/>
			<?php endif; ?>
			<?php for ($i = 0; $i < $i_MaxDis; $i++) : ?>
					<img src="<?php echo SITE_WEBROOT; ?>img/stars_disabled.png" width="15"/>
			<?php endfor; ?>
				<span style="float: right;">&nbsp;&nbsp;<?php echo $i_TotalReview; ?> мнения</span>
				<div style="clear: both;"></div>
        </div>
		
		
        <div>
   
        <?php
			$url = $listing["Listing"]["video"];
			$url_pos = strpos($url, 'v=');
			$url_pos = (int)$url_pos + 2;
			$url_len =  strlen($url);
			$vidID = substr($url, $url_pos, $url_len);
			if( isset($vidID) && !empty($vidID) ) {
		?>
                
                <iframe type="text/html" width="400" height="230" src="http://www.youtube.com/embed/<?php echo $vidID; ?>?wmode=opaque" frameborder=”0″ allowfullscreen></iframe>
		<?php } ?>
    
        </div>
		
	</div>
    <div class="list-content">
		<div style="float: left; padding: 10px;">
				<?php if( isset( $listing["Listing"]["photo"] ) && !empty($listing["Listing"]["photo"]) ) {
							$files = explode(',',  $listing["Listing"]["photo"]);
							foreach(  $files as $v ){
				 ?>
				<img src="<?php echo  SITE_WEBROOT; ?>/uploads/<?php echo $v ?>" width="160px" hieght="120px" />
				<?php }} else { ?>
				<img src="http://open.thumbshots.org/image.pxf?url=<?php echo urlencode($listing['Listing']['url']); ?>" />
				<?php } ?>
		</div>
		<p>
			<?php echo htmlspecialchars($listing['Listing']['description']); ?>
		</p>
    </div>
    <div class="list-contact">
	 <p>
            <strong>Телефон:</strong>
        <?php
        echo htmlspecialchars($listing['Listing']['landline']);
        ?>
        </p>
        <p>
            <strong>GSM:</strong>
    <?php
    echo htmlspecialchars($listing['Listing']['mobile']);
    ?>
        </p>
        <p>
            <strong>Пощенски код:</strong>
            <?php
            echo htmlspecialchars($listing['Listing']['postcode']);
            ?>
        </p>
        <p><strong>Адрес:</strong>
            <?php
            echo htmlspecialchars($listing['Listing']['address_1']);
            $ts=($listing['Listing']['train_stations']);
            $bs=($listing['Listing']['bus_stations']);
            $ss=($listing['Listing']['subway_stations']);

            ?></p>
        <? if ($ts!=''){?>
        <strong>Train Station</strong>
        <div><?=$ts?></div>
        <?} if ($bs!=''){?>
        <strong>Bus Station</strong>
        <div><?=$bs?></div>
        <?} if ($ss!=''){?>
        <strong>Subway Station</strong>
        <div><?=$ss?></div>
        <?} ?>
        <? if ($_nearby!=''){?>
        <strong>Places Nearby</strong>
        <div><?=$_nearby?></div>
        <?}?>
         
         <? if ($listing['Listing']['nearbystreets']!=''){?>
         <div><strong>Nearby Streets</strong>
        <?=$listing['Listing']['nearbystreets']?></div>
        <?}?>
        <img src="data:image/jpeg;base64,<?= ($listing['Listing']['streetview'])?>" alt="Street view image for <?= $listing['Listing']['title']?> with address <?= $listing['Listing']['address_1']?>" title="Street view image for <?= $listing['Listing']['title']?> with address <?= $listing['Listing']['address_1']?>"/>
        <div style="width:90%; height: 300px;"name="sv" id="sv"></div>
        <p>
        <strong></strong>
            <?php
            echo htmlspecialchars($listing['Listing']['address_2']);
            ?>
    </p>
    <br />
    <p>
        <strong>Категория:</strong>
            <?php
            $i = count($listing["CATEGORY_PATH"]) - 1;
            echo '<a href="' . SITE_WEBROOT . $listing["Location"]["url_title"] . '/' . $listing["CATEGORY_PATH_URL"][$i] . '">' . htmlspecialchars($listing["CATEGORY_PATH"][$i]["Category"]["name"]) . ' в ' . htmlspecialchars($listing["Location"]["name"]) . '</a>';
            ?>
    </p>
    <p>
        <strong>Уеб сайт:</strong>
            <?php
            if (__startsWith($listing["Listing"]["url"], "http://") || __startsWith($listing["Listing"]["url"], "https://")) {
                $httpString = '';
            } else {
                $httpString = 'http://';
            }
            echo '<a target="_blank" href="' . $httpString . $listing["Listing"]["url"] . '">' . htmlspecialchars($listing['Listing']['title']) . '</a>';
            ?>
    </p>
    <p>
        <strong>Email:</strong>
            <?php
            echo '<a target="_blank" href="mailto:' . $httpString . $listing["Listing"]["email"] . '">' . htmlspecialchars($listing['Listing']['email']) . '</a>';
            ?>
    </p>
    <p>
        <strong>Opening Hours:</strong>
            <?php
            $dayss = array('Every day', 'Weekdays', 'Weekends', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
            $day = $listing["Listing"]["opening_day"];
            $day_array = explode(',', $day);
            $day_array_values = array();
            foreach( $day_array as $v){
                $day_array_values[] = $dayss[$v];
            }


            $hours = array();
				for($i=1; $i<25; $i++){
                                    if( $i < 10) {
					$hours[$i] = "0".$i.":00";
                                    } else {
                                        $hours[$i] = $i.":00";
                                    }
				}
            $hr1 = $listing["Listing"]["opening_hour_start"];
            $hr1 = explode(',', $hr1);
            $hr1_values = array();
            foreach( $hr1 as $v) {
                $hr1_values[] = $hours[$v];
            }

            $hr2 = $listing["Listing"]["opening_hour_end"];
            $hr2 = explode(',', $hr2);
            $hr2_values = array();
            foreach( $hr2 as $v) {
                $hr2_values[] = $hours[$v];
            }

            echo "<ul>";
            $i=0;
            foreach( $day_array_values as $v) {
                echo "<li>".$day_array_values[$i]."&nbsp;&nbsp;".$hr1_values[$i]."&nbsp;-&nbsp;".$hr2_values[$i];
                $i++;
            }
            echo "</ul>";
            ?>
    </p>
    <p>
        <strong>Payment Methods:</strong>
            <?php
            $pay_method = array('Cash,Cheques', 'Direct Debit', 'Credit Cards', 'PayPal', 'Bank Transfers', 'Skrill checkbox');
            $pay = $listing["Listing"]["payment_method"];
            $pay = explode(',', $pay);
            foreach($pay as $val ){
                echo $pay_method[$val].",";
            }
            ?>
    </p>
    <p>
        <strong>Good For:</strong>
            <?php
            $goodFor = array('Children', 'Groups', 'Families', 'Dates', 'Disabled People', 'Business Meetings', 'Birthdays','Parties');
            $forg = $listing["Listing"]["good_for"];
            $forg = explode(',', $forg);
            foreach($forg as $val){
                echo $goodFor[$val].",";
            }
            ?>
    </p>
    <p>
        <strong>Access:</strong>
            <?php
            $access = array('Free Parking', 'Paid Parking', 'Disability Access');
            $acc = $listing["Listing"]["access"];
            $acc = explode(',', $acc);
            foreach($acc as $val){
                echo $access[$val].",";
            }

            ?>
    </p>
    <p>
        <strong>Year Established:</strong>
            <?php
            $years = array();
		    for($i = 1900; $i< 2014; $i++){
				$years[$i] =  $i;
			}
            $yr = $listing["Listing"]["year_established"];
            $year = $years[$yr];

            echo $year;
            ?>
    </p>
    <p>
        <strong>Number Of Employee:</strong>
            <?php
            $employee = array('1-5', '5-10', '10-20', '20-50', '50-100', 'over 100');
            $emp = $listing["Listing"]["number_of_employee"];
            $employee = $employee[$emp];

            echo $employee;
            ?>
    </p>
    
    
   
    <br />
    <p>
        <strong>Ключови думи:</strong>
            <?php

            foreach ($listing["ListingTag"] as $listingTag) {
                echo '<a href="' . SITE_WEBROOT . 'tags/' . $listingTag["url_title"] . '">' . htmlspecialchars($listingTag["name"]) . '</a>';
                echo '&nbsp;';
            }
            ?>
    </p>
    <br />
    <ul>
        <li>
        <?php
        $categoryIndex = count($listing["CATEGORY_PATH_URL"]) - 1;
        echo '<a href="' . SITE_WEBROOT . $listing["CATEGORY_PATH_URL"][$categoryIndex] . '">' . htmlspecialchars(' ' . $listing["CATEGORY_PATH"][$categoryIndex]["Category"]["name"] . ' ') . '</a>';
        ?>
        </li>
		<li>
		<?php echo '<a href="' . SITE_WEBROOT . '">' . htmlspecialchars('Бизнес каталог с фирми') . '</a>'; ?>
		</li>
    </ul>
	</div> 
	<div class="list-comment">
        <?php echo $this->element('review'); ?>
        <?php echo $this->element('listing_review'); ?>
		<?php } ?>			
		<?php echo $yell; ?>
	</div>
</div>

</div>	
<div class="center-right">
								<div class="widget-one">
								</div>
								<div class="widget-one">
									<ul>
										<li>
											
										<a><img src="../image/list.png"/></a>
										<h3>Bar & Dinner</h3>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<a><p>5 Start<p></a>
											
											
										</li>
										<li>
											
										<a><img src="../image/list.png"/></a>
										<h3>Bar & Dinner</h3>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<a><p>5 Start<p></a>
											
											
										</li>
						
										<li>
											
										<a><img src="../image/list.png"/></a>
										<h3>Bar & Dinner</h3>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<a><p>5 Start<p></a>
											
											
										</li>
										<li>											
										<a><img src="../image/list.png"/></a>
										<h3>Bar & Dinner</h3>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
													<img src="../image/stars_disabled.png"/>
										<p>5 Start<p>
											
											
										</li>
										<div class="clear"></div>
									</ul>
								</div>
							</div>
